#import <appkit/appkit.h>
#import "DrawView.h"
#import "AShape.h"

@implementation DrawView

-(BOOL)acceptsFirstMouse {return YES;}

-initFrame:(NXRect const *)r
{
	[super initFrame:r];
	fill = NO;
	currentShade = 0.0;
	shapeList = [[List alloc] init];
	shapeClassList = [[List alloc] init];
	shapeClass = nil;
	return self;
}

-takeShadeFrom:sender
{
    currentShade=[sender floatValue];
    return self;
}
 
-takeFillFrom:sender
{
    fill = [sender selectedTag];
    return self;
}

-setDrawType:(int)type
{
	if(type == -1)
		shapeClass = nil;	//If -1, selection arrow was chosen.
	else
		shapeClass = [shapeClassList objectAt:type];  //else a new shape.
	return self;
}

-(int)addShapeClass:class
{
	[shapeClassList addObject:class];
	return ([shapeClassList count]-1);  //index of last one added
}

-makeNewShape:(NXRect *)bbox
{
	id	newShape;
	if(shapeClass){
		newShape=[[shapeClass alloc] initShapeWithBBox:bbox];
		[newShape setFill:fill];
		[newShape setShade:currentShade];
		return newShape;
	}
	else return nil;
}

-addShape:newObject
{
    if (newObject !=nil)
	[shapeList addObject:newObject];
    return newObject;
}

-mouseDown:(NXEvent *)e
{
	int oldMask;
	NXRect r2;
	NXPoint pt;
	id aShape;
    
	oldMask = [window addToEventMask:NX_MOUSEDRAGGEDMASK];
	[self lockFocus];
		pt = e->location;
		[self convertPoint:&pt fromView:nil];
		
		/* If selection arrow, then just go select any object moused on. */
		if(shapeClass == nil)
			[self selectMouseAction:&pt];

		/* If a drawing tool, then drag out a new shape. */
		else {
			NXSetRect(&r2,pt.x,pt.y,0.0,0.0);
			aShape = [self makeNewShape:&r2];
			if(aShape){
				[self dragOutShape:aShape startingRect:&r2];
				[self addShape:aShape];
				[aShape drawShape];
			}
		}
	[self unlockFocus];
	[window flushWindow];
	[window setEventMask:oldMask];
	return self;
}

-selectMouseAction:(NXPoint *)pt
{
	return self;
}

-dragOutShape:(id)aShape startingRect:(NXRect *)r2
{
    NXEvent *e;
    NXPoint	pt;
    
    e=[NXApp getNextEvent:NX_MOUSEUPMASK|NX_MOUSEDRAGGEDMASK];
    while (e->type==NX_MOUSEDRAGGED){
	pt = e->location;
	[self convertPoint:&pt fromView:nil];
	r2->size.width = pt.x - r2->origin.x;
	r2->size.height = pt.y - r2->origin.y;
	[aShape setBbox:r2];
	PSnewinstance();   
	[superview autoscroll:e];
	PSsetinstance(YES);
		if(r2->size.height && r2->size.width)
	 		[aShape drawShape];
	PSsetinstance(NO);
	e=[NXApp getNextEvent:NX_MOUSEUPMASK|NX_MOUSEDRAGGEDMASK];
    }
    PSnewinstance();
    return self;
}

-drawSelf:(NXRect *)r :(int)c;
{
	int i;
	PSsetgray(NX_WHITE);
	NXRectFill(r); 
	for(i=0; i<[shapeList count]; i++)
		[[shapeList objectAt:i] drawShape];
	return self;
}

@end